package com.example.day44.pop;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.example.day44.R;

import java.util.ArrayList;

/**
 * POPUPWindow
 * 注意事项
 * 1.只能使用在Activity当中
 * 2.如果你想进入界面就展示popupwindow 就在onWindowFocusChanged方法调用show方法
 */
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    PopupWindow popupWindow;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    /**
     *
     */
    private void init() {
        btn = (Button) this.findViewById(R.id.btn);
        btn.setOnClickListener(this);
        /**
         * View contentView,
         * int width,
         * int height,
         * boolean focusable
         */


        View view = getLayoutInflater().inflate(R.layout.pop_content_layout, null);
        ListView lv = (ListView) view.findViewById(R.id.listview);
        ArrayList<String> list = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            list.add("POP" + i);
        }
        ImageView imageView = (ImageView) view.findViewById(R.id.empty);
        lv.setEmptyView(imageView);
        lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, list));

        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
        //设置popwindow的背景颜色
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.RED));
        //点击popwindow以外的空间,pop消失

//        popupWindow.setOutsideTouchable(true);
//        popupWindow = new PopupWindow(view);
    }

    @Override
    public void onClick(View v) {
//        popupWindow.showAsDropDown(btn);
//        popupWindow.showAsDropDown(btn,100,300);
        /**
         *  参数一 必须是父类容器Activity  view
         *   int gravity,
         *   int x, x轴偏移量
         *   int y y轴偏移量
         */
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
        }


    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
//        if (hasFocus) {
//            popupWindow.showAsDropDown(btn);
//        }
    }
}
